<template>
  <!-- 轨迹路径 赛项轨迹路径 -->
  <div class="pageWrap">
    <el-tabs type="card" v-model="activeGroupI" @tab-click="groupChange">
      <el-tab-pane v-for="(v,i) in groupArr" :key="i" :label="v.name" :name="'g'+i"></el-tab-pane>
    </el-tabs>
    <el-upload :action="upLoadUrl" :show-file-list="false" :on-success="(value)=> fileSuccess(value)"
      :before-upload="(file)=> beforeUpload(file)" name="file">
      <el-button size="small" type="primary">点击上传</el-button>
      <span slot="tip" class="tip">只能上传KML文件，且不超过2MB</span>
    </el-upload>
    <div id="AMapContainer" ref="allmap" v-loading="maploading"></div>
  </div>
</template>

<script>
const getDistance = (lat1, lng1, lat2, lng2) => {
  var radLat1 = lat1 * Math.PI / 180.0;
  var radLat2 = lat2 * Math.PI / 180.0;
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137; // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000;
  return Number(s);
}
  export default {
    data() {
      return {
        maploading: false,
        activeGroupI: "g0",
        groupArr: [],
        upLoadUrl: this.$url + "/sbr/match/uploadKml",
        map: "",
      };
    },
    methods: {
      // 获取赛项
      getGroupArr() {
        this.$axios
          .get("/sbr/match/getMatchInfos/" + sessionStorage.getItem("MandA"))
          .then((res) => {
            let rr = res.data.data;
            this.groupArr = rr.matchInfoLists;
            this.groupChange();
          });
      },
      // 切换赛项 地图切换
      groupChange() {
        let ii = this.activeGroupI.replace(/g/g, "");
        let FN = this.groupArr[ii].kmlFile;
        if (FN) {
          this.$axios.get("/sbr/match/run/getKml?fileName=" + FN).then((res) => {
            this.cavLine(res.data.data.kmlProperty);
          });
        } else this.cavLine("");
      },
      beforeUpload(file) {
        let ii = this.activeGroupI.replace(/g/g, "");
        let oldF = this.groupArr[ii].kmlFile; // 如果有旧的删除旧的
        if (oldF) {
          this.$axios.get("/sbr/match/delImg?fileName=" + oldF);
        }
        let a = file.name.split(".");
        const isKML = a[a.length - 1] == "KML" || a[a.length - 1] == "kml";
        const isLt1M = file.size / 1024 / 1024 < 2;

        if (!isKML) {
          this.$message.error("上传文件只能是 KML 格式!");
        }
        if (!isLt1M) {
          this.$message.error("上传文件大小不能超过 2MB!");
        }
        return isKML && isLt1M;
      },
      fileSuccess(v) {
        console.log(v);
        let rr = v.data;
        let ii = this.activeGroupI.replace(/g/g, "");
        let gId = this.groupArr[ii].id;
        let oo = {
          kmlFile: rr.fileName,
          id: gId,
        };
        this.maploading = true;
        this.$axios.post("/sbr/match/putMatchInfoKml", oo).then((res) => {
          this.cavLine(rr.kml);
          this.maploading = false;
        });
      },
      // 地图初始
      getMap() {
        // 百度地图API功能
        // this.map = new BMap.Map(this.$refs.allmap); // 创建Map实例
        // this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
        // var mapStyle = {
        //   features: ["road", "building", "water", "land"], //隐藏地图上的"poi",
        //   style: "googlelite",
        // };
        // this.map.setMapStyle(mapStyle);
        // this.map.addEventListener("zoomend", 12);
        // this.map.enableScrollWheelZoom(true);
        this.map = new AMap.Map("AMapContainer", {
          resizeEnable: true
        })
      },
      //画轨迹
      cavLine(v) {
        this.map.clearMap()
        if (v != "") {
          let polylinePath = [];
          if (v.kmlLines.length > 0) {
            v.kmlLines[0].points.forEach((vv) => {
              polylinePath.push(new AMap.LngLat(vv.longitude, vv.latitude));
            });
            this.setZoom(v.kmlLines[0].points);
          } else {
            v.kmlPoints.forEach((vv) => {
              polylinePath.push(
                new AMap.LngLat(vv.points[0].longitude, vv.points[0].latitude)
              );
            });
          }
          let polyline = new AMap.Polyline({
            path: polylinePath,
            strokeColor:"red",
            strokeWeight:3
          });
        this.map.add(polyline)
        }
      },
      //根据原始数据计算中心坐标和缩放级别，并为地图设置中心坐标和缩放级别。
      setZoom(points) {
        if (points.length > 0) {
          var maxLng = points[0].longitude;
          var minLng = points[0].longitude;
          var maxLat = points[0].latitude;
          var minLat = points[0].latitude;
          var res;
          for (var i = points.length - 1; i >= 0; i--) {
            res = points[i];
            if (res.longitude > maxLng) maxLng = res.longitude;
            if (res.longitude < minLng) minLng = res.longitude;
            if (res.latitude > maxLat) maxLat = res.latitude;
            if (res.latitude < minLat) minLat = res.latitude;
          }
          var cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
          var cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
          this.map.setCenter([cenLng,cenLat])
          // var zoom = this.getZoom(maxLng, minLng, maxLat, minLat)
          this.map.setZoom(12);
          // this.map.centerAndZoom(new BMap.Point(cenLng, cenLat), zoom);
          // return {
          //   cenLng,
          //   cenLat,
          //   zoom,
          // };
        }
      },
      //算出中心点坐标
      getZoom(maxLng, minLng, maxLat, minLat) {
        var zoom = [
          "50",
          "100",
          "200",
          "500",
          "1000",
          "2000",
          "5000",
          "10000",
          "20000",
          "25000",
          "50000",
          "100000",
          "200000",
          "500000",
          "1000000",
          "2000000",
        ]; //级别18到3。
        var distance =getDistance(maxLat,maxLng,minLat,minLng)
        // var pointA = new BMap.Point(maxLng, maxLat); // 创建点坐标A
        // var pointB = new BMap.Point(minLng, minLat); // 创建点坐标B
        // var distance = this.map.getDistance(pointA, pointB).toFixed(1); //获取两点距离,保留小数点后两位
        for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
          if (zoom[i] - distance > 0) {
            return 18 - i + 3; //之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
          }
        }
      },
    },
    mounted() {
      this.getMap();
      this.getGroupArr();
    },
  };
</script>
<style scoped>
  /* @import url(); 引入公共css类 */
  .tip {
    margin-left: 8px;
  }

  #AMapContainer {
    width: 100%;
    height: 500px;
  }

  #AMapContainer>>>.anchorBL {
    display: none;
  }
</style>